package com.roobo.demo;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.util.Log;

import java.io.IOException;

/**
 * 播放器
 */

public class MyMediaPlayer implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener {

    public static final String TAG=MyMediaPlayer.class.getSimpleName();

    private static class MyMediaPlayerSingleInstance {
        private static MyMediaPlayer sInstance = new MyMediaPlayer();
    }

    public static MyMediaPlayer getInstance() {
        return MyMediaPlayerSingleInstance.sInstance;
    }

    public interface PlayStateListener {
        void onPrepare();

        void onPlaying();

        void onPlayCompletion();

        void onPlayError(String error);
    }

    private MediaPlayer mMediaPlayer;
    private PlayStateListener mPlayStateListener;

    private MyMediaPlayer() {
    }


    private void initMediaPlayer() {
        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.setOnCompletionListener(this);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        }
        mMediaPlayer.reset();
    }

    public void setPlayStateListener(PlayStateListener mPlayStateListener) {
        this.mPlayStateListener = mPlayStateListener;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        if (!mp.isPlaying()) {
            mp.start();
            if (mPlayStateListener != null) {
                mPlayStateListener.onPlaying();
            }
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        if (mPlayStateListener != null) {
            mPlayStateListener.onPlayCompletion();
        }
    }

    /**
     * 准备音频
     *
     * @param url
     */
    public void prepare(String url) {
        try {
            initMediaPlayer();
            mMediaPlayer.setDataSource(url);
            mMediaPlayer.prepare();//预加载音频
            if (mPlayStateListener != null) {
                mPlayStateListener.onPrepare();
            }
        } catch (IOException e) {
            Log.d(TAG,"prepare e.getLocalizedMessage:"+e.getLocalizedMessage());
            if (mPlayStateListener != null) {
                mPlayStateListener.onPlayError(e.getLocalizedMessage());
            }
        }
    }

    /***
     * 暂停播放
     */
    public void pause() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
        }
    }

    /**
     * 恢复播放
     */
    public void resume() {
        if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
            mMediaPlayer.start();
        }
    }

    /***
     * 释放player
     */
    public void release() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
}
